<template>
  <div class="menu-management">
    <div class="page-header">
      <h2>菜单管理</h2>
    </div>

    <!-- 搜索栏 -->
    <div class="search-bar">
      <el-form :model="searchForm" inline @submit.prevent="handleSearch">
        <el-form-item label="菜单名称">
          <el-input 
            v-model="searchForm.name" 
            placeholder="请输入菜单名称" 
            clearable 
            @keyup.enter="handleSearch"
            @clear="handleReset"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">
            <el-icon>
              <Search />
            </el-icon>
            搜索
          </el-button>
          <el-button @click="handleReset">重置</el-button>
          <el-button @click="handleExpandAll">展开全部</el-button>
          <el-button @click="handleCollapseAll">收起全部</el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 菜单表格 -->
    <div class="table-container">
      <el-table ref="menuTable" :data="displayData" v-loading="loading" row-key="id"
        :tree-props="{ children: 'children', hasChildren: 'hasChildren' }" border stripe :table-layout="'auto'">
        <el-table-column prop="id" label="菜单id" mix-width="100" />
        <el-table-column prop="name" label="菜单名称" mix-width="150" />
        <el-table-column prop="icon" label="图标" mix-width="100" align="center">
          <template #default="{ row }">
            <el-icon v-if="row.icon" :size="16">
              <component :is="row.icon" />
            </el-icon>
            <span v-else>-</span>
          </template>
        </el-table-column>
         <el-table-column label="状态" mix-width="120" align="center">
          <template #default="{ row }">
            <div class="status-control">
              <el-switch v-model="row.isActive" :active-value="true" :inactive-value="false"
                @change="handleToggleStatus(row)" />
              <span class="status-text">
                {{ row.isActive ? '启用' : '禁用' }}
              </span>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="路径" width="150" prop="path"/>
        <el-table-column prop="sort" label="排序" width="80" align="center" />
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button size="small" @click="handleEdit(row)" icon="Edit">编辑</el-button>
            <el-button size="small" type="danger" @click="handleDelete(row)" icon="Delete">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <!-- 编辑对话框 -->
    <el-dialog :title="dialogTitle" v-model="dialogVisible" width="700px" :before-close="handleCloseDialog">
      <el-form ref="menuForm" :model="menuFormData" :rules="menuFormRules" label-width="100px">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="父级菜单" prop="parentId">
              <el-tree-select v-model="menuFormData.parentId" :data="parentMenuOptions"
                :props="{ value: 'id', label: 'name', children: 'children' }" placeholder="请选择父级菜单" clearable
                check-strictly />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="菜单名称" prop="name">
              <el-input v-model="menuFormData.name" placeholder="请输入菜单名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="菜单图标" prop="icon">
              <el-input v-model="menuFormData.icon" placeholder="请输入图标名称">
                <template #append>
                  <el-button @click="iconSelectVisible = true">选择</el-button>
                </template>
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20" v-if="menuFormData.type !== 'button'">
          <el-col :span="12">
            <el-form-item label="路由路径" prop="path">
              <el-input v-model="menuFormData.path" placeholder="请输入路由路径" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="组件路径" prop="component" v-if="menuFormData.type === 'menu'">
              <el-input v-model="menuFormData.component" placeholder="请输入组件路径" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="排序" prop="sort">
              <el-input-number v-model="menuFormData.sort" :min="0" :max="999" placeholder="排序号" style="width: 100%" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="是否启用">
              <el-switch v-model="menuFormData.isActive" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="是否缓存" v-if="menuFormData.type === 'menu'">
              <el-switch v-model="menuFormData.keepAlive" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <el-button @click="handleCloseDialog">取消</el-button>
        <el-button type="primary" @click="handleSubmit" :loading="submitLoading">
          确认
        </el-button>
      </template>
    </el-dialog>

    <!-- 图标选择对话框 -->
    <el-dialog title="选择图标" v-model="iconSelectVisible" width="600px">
      <div class="icon-selector">
        <div v-for="icon in iconList" :key="icon" class="icon-item" :class="{ active: menuFormData.icon === icon }"
          @click="selectIcon(icon)">
          <el-icon :size="20">
            <component :is="icon" />
          </el-icon>
          <span>{{ icon }}</span>
        </div>
      </div>
      <template #footer>
        <el-button @click="iconSelectVisible = false">取消</el-button>
        <el-button type="primary" @click="confirmIcon">确认</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search } from '@element-plus/icons-vue'
import { useMenuStore } from '@/stores/menu'

// 响应式数据
const loading = ref(false)
const tableData = ref([])
const displayData = ref([])
const dialogVisible = ref(false)
const iconSelectVisible = ref(false)
const submitLoading = ref(false)
const currentMenu = ref(null)
const menuForm = ref()
const menuTable = ref()
const selectedIcon = ref('')
const useStore = useMenuStore()

// 搜索表单
const searchForm = ref({
  name: ''
})

// 菜单表单数据
const menuFormData = reactive({
  parentId: null,
  id: null,
  name: '',
  icon: '',
  path: '',
  sort: 0,
  isActive: true
})

// 图标列表
const iconList = [
  'Menu', 'User', 'Setting', 'Document', 'Monitor',
  'Lock', 'Files', 'Plus', 'Search', 'HomeFilled', 'Management', 'Odometer'
]

// 上级菜单选项
const parentMenuOptions = ref([
  {
    id: null,
    name: '顶级菜单',
    children: []
  }
])

// 计算属性
const dialogTitle = '编辑菜单'

// 表单验证规则
const menuFormRules = {
  name: [
    { required: true, message: '请输入菜单名称', trigger: 'blur' },
    { min: 2, max: 20, message: '菜单名称长度在 2 到 20 个字符', trigger: 'blur' }
  ],
  path: [
    { required: true, message: '请输入路由路径', trigger: 'blur' }
  ],
  sort: [
    { required: true, message: '请输入排序号', trigger: 'blur' }
  ]
}

// 构建父级菜单选项（排除当前菜单及其子菜单）
const buildParentOptions = (data, excludeId = null) => {
  const result = []
  
  // 递归查找所有子菜单ID
  const getAllChildIds = (menu) => {
    const ids = [menu.id]
    if (menu.children && menu.children.length > 0) {
      menu.children.forEach(child => {
        ids.push(...getAllChildIds(child))
      })
    }
    return ids
  }
  
  data.forEach(item => {
    // 如果当前菜单是需要排除的菜单或其子菜单，跳过
    if (excludeId && getAllChildIds(item).includes(excludeId)) {
      return
    }
    
    const option = {
      id: item.id,
      name: item.name,
      children: item.children && item.children.length > 0 ? buildParentOptions(item.children, excludeId) : []
    }
    result.push(option)
  })
  return result
}

//获取菜单树
const loadData = async () => {
  loading.value = true
  try {
    // 获取菜单树形数据
    const treeData = await useStore.getmenutree()
    console.log('菜单树数据:', treeData)
    
    // 直接使用树形数据
    tableData.value = treeData
    displayData.value = treeData
    
    // 构建父级菜单选项（初始加载时不排除任何菜单）
    parentMenuOptions.value = [
      { id: null, name: '顶级菜单', children: [] },
      ...buildParentOptions(treeData)
    ]
  } catch (error) {
    console.error('加载菜单数据失败:', error)
    ElMessage.error('加载菜单数据失败')
  } finally {
    loading.value = false
  }
}

const handleSearch = () => {
  // 在树形结构中搜索菜单
  if (!searchForm.value.name.trim()) {
    displayData.value = tableData.value
    return
  }
  
  // 递归搜索函数
  const searchInTree = (menus, keyword) => {
    const result = []
    menus.forEach(menu => {
      if (menu.name.includes(keyword)) {
        // 如果当前菜单匹配，包含所有子菜单
        result.push(menu)
      } else if (menu.children && menu.children.length > 0) {
        // 如果当前菜单不匹配，递归搜索子菜单
        const filteredChildren = searchInTree(menu.children, keyword)
        if (filteredChildren.length > 0) {
          // 如果子菜单有匹配的，包含当前菜单但只显示匹配的子菜单
          result.push({
            ...menu,
            children: filteredChildren
          })
        }
      }
    })
    return result
  }
  
  displayData.value = searchInTree(tableData.value, searchForm.value.name)
}

const handleReset = () => {
  searchForm.value = {
    name: ''
  }
  displayData.value = tableData.value
}

const handleExpandAll = () => {
  if (menuTable.value) {
    const expandRows = (data) => {
      data.forEach(row => {
        menuTable.value.toggleRowExpansion(row, true)
        if (row.children && row.children.length > 0) {
          expandRows(row.children)
        }
      })
    }
    expandRows(displayData.value)
  }
}

const handleCollapseAll = () => {
  if (menuTable.value) {
    const collapseRows = (data) => {
      data.forEach(row => {
        menuTable.value.toggleRowExpansion(row, false)
        if (row.children && row.children.length > 0) {
          collapseRows(row.children)
        }
      })
    }
    collapseRows(displayData.value)
  }
}

//获取修改数据值
const handleEdit = (row) => {
  currentMenu.value = row
  Object.assign(menuFormData, {
    parentId: row.parentId || null,
    id: row.id,
    name: row.name,
    icon: row.icon,
    path: row.path,
    sort: row.sort,
    isActive: row.isActive
  })
  
  // 重新构建父级菜单选项，排除当前菜单及其子菜单
  parentMenuOptions.value = [
    { id: null, name: '顶级菜单', children: [] },
    ...buildParentOptions(tableData.value, row.id)
  ]
  
  dialogVisible.value = true
}

//删除菜单行
const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除菜单 "${row.name}" 吗？删除后子菜单也将被删除！`,
      '提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )

    // 删除API调用
    await useStore.deleteMenu(row.id)
    ElMessage.success('删除成功')
    loadData()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败')
    }
  }
}

//编辑菜单行
const handleSubmit = async () => {
  if (!menuForm.value) return

  try {
    await menuForm.value.validate()
    submitLoading.value = true

    const updateData = {
      name: menuFormData.name,
      parentId: menuFormData.parentId,
      isActive: menuFormData.isActive,
      icon: menuFormData.icon,
      path: menuFormData.path,
      sort: menuFormData.sort
    }
    
    console.log('更新菜单数据:', updateData)

    await useStore.updateMenu(menuFormData.id, updateData)

    ElMessage.success('编辑成功')
    dialogVisible.value = false
    loadData()
  } catch (error) {
    console.error('编辑菜单失败:', error)
    if (error !== false) {
      ElMessage.error('编辑失败')
    }
  } finally {
    submitLoading.value = false
  }
}

const handleToggleStatus = async (row) => {
  const action = row.isActive ? '启用' : '禁用'
  try {    
    await useStore.updateMenu(row.id, {
      name: row.name,
      isActive: row.isActive,
      icon: row.icon,
      path: row.path,
      sort: row.sort
    })
    ElMessage.success(`${action}成功`)
    
    // 成功后重新加载数据以确保状态同步
    await loadData()
  } catch (error) {
    // 如果操作失败，还原开关状态
    row.isActive = !row.isActive
    ElMessage.error(`${action}失败`)
    console.error('更新菜单状态失败:', error)
  }
}

const handleCloseDialog = () => {
  dialogVisible.value = false
  resetFormData()
  if (menuForm.value) {
    menuForm.value.resetFields()
  }
}

const resetFormData = () => {
  Object.assign(menuFormData, {
    parentId: null,
    id: null,
    name: '',
    icon: '',
    path: '',
    sort: 0,
    isActive: true
  })
}

const selectIcon = (icon) => {
  selectedIcon.value = icon
}

const confirmIcon = () => {
  menuFormData.icon = selectedIcon.value
  iconSelectVisible.value = false
}
const yingshe =async()=>{
 // 设你已经通过 axios 获取到了数据
const topMenus = await useStore.getmenutree();
const allMenus = await useStore.getMenu();
const parentChildMap = allMenus.reduce((acc, menu) => {
  const { parentId, id } = menu;
  if (!acc[parentId]) {
    acc[parentId] = [];
  }
  acc[parentId].push(id);
  return acc;
}, {});
}
// 生命周期
onMounted(() => {
  loadData()
})
</script>

<style scoped>
.menu-management {
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.page-header h2 {
  margin: 0;
  color: #333;
}

.pagination-container {
  display: flex;
  justify-content: flex-end;
}

.search-bar {
  background: #f5f5f5;
  padding: 20px;
  border-radius: 8px;
  margin-bottom: 20px;
}

.table-container {
  background: white;
  border-radius: 8px;
  overflow: hidden;
  margin-bottom: 20px;
}

.icon-selector {
  display: grid;
  grid-template-columns: repeat(5, 1fr);
  gap: 10px;
  max-height: 300px;
  overflow-y: auto;
}

.icon-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 10px;
  border: 1px solid #ddd;
  border-radius: 4px;
  cursor: pointer;
  transition: all 0.3s;
}

.icon-item:hover {
  border-color: #409eff;
  background: #f0f9ff;
}

.icon-item.active {
  border-color: #409eff;
  background: #409eff;
  color: white;
}

.icon-item span {
  margin-top: 5px;
  font-size: 12px;
}

:deep(.el-table) {
  border-radius: 8px;
}

:deep(.el-dialog__header) {
  border-bottom: 1px solid #eee;
  padding-bottom: 15px;
}

:deep(.el-form-item) {
  margin-bottom: 18px;
}

.select-type {
  width: 100px;
}

.status-control {
  display: flex;
  align-items: center;
  gap: 8px;
}

.status-text {
  font-size: 12px;
  color: #666;
}
</style>
